package com.mrd.gtimp.business.action;

import com.mrd.constant.BaseTypeConstant;
import com.mrd.constant.MsgConstants;
import com.mrd.constant.RoleConstants;
import com.mrd.constant.SystemConstants;
import com.mrd.exception.QueryException;
import com.mrd.exception.SaveException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.base.service.UserBiz;
import com.mrd.gtimp.business.TrailCTAddressDTO;
import com.mrd.gtimp.business.entity.CancelReason;
import com.mrd.gtimp.business.entity.Container;
import com.mrd.gtimp.business.entity.GoodAddress;
import com.mrd.gtimp.business.entity.RejectContent;
import com.mrd.gtimp.business.entity.Trail;
import com.mrd.gtimp.business.service.CancelReasonBiz;
import com.mrd.gtimp.business.service.RejectContentBiz;
import com.mrd.gtimp.business.service.TrailBiz;
import com.mrd.util.ReflectUtil;
import com.mrd.util.sendEmail.SendEmail;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import javax.annotation.Resource;

import static com.mrd.util.AdminUtil.checkRight;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */

@Controller
@RequestMapping("/business")
public class TrailAction {
    private static final long serialVersionUID = 1L;
    @Resource
    private TrailBiz trailBiz;

    @Resource
    private UserBiz userBiz;

    @Resource
    private CancelReasonBiz cancelReasonBiz;

    @Resource
    private RejectContentBiz rejectContentBiz;

    /**
     * 存放拖车单中去重以后的所有柜
     */
    private List<Container> containers;
    /**
     * 拖车单的柜的统计，格式为<柜型，数量>
     */
    private Map<String, Integer> containerTotle;
    /**
     * 用于标识是否为载入拖车历史单的页面
     */
    private String loadPage;
    /**
     * 修改页面传回的id
     */
    private String id;
    /**
     * 判断页面的标识
     */
    private String identify = "";

    /**
     * 用于导出exl表格
     */
    private InputStream ExlStream;

    /**
     * 设置导出exl文件的文件名
     */
    private String exlFileName;

    private String trailState;

    /**
     * 默认访问入口
     */
    @RequestMapping("/trail-main")
    public String main() {
        return "/gtimp/trail/traillist";
    }

    /**
     * 默认新增修改入口
     */
    @RequestMapping("/trail-manage")
    public String manage() {
        return "manage";
    }

    /**
     * 新增或修改信息
     */
    @RequestMapping("/trail-saveOrUpdate")
    @ResponseBody
    public Result saveOrUpdate(Trail trail) {
        Result msg;
        if (checkRight(RoleConstants.SUP_CUSTOMER_SAVE)) {
            try {
                if (StringUtils.isEmpty(trail.getId())) { // 新增操作
                    // trail.setCOM_ID(user.getCompany().getId());
                    // trail.setCREATOR(user.getAccount());
                    // trail.setCTIME(new Date());
                    // trail.setID(null);
                } else { // 修改操作
                    // trail.setMODIFIER(user.getAccount());
                    // trail.setMTIME(new Date());
                }
                trailBiz.saveOrupdateEntity(trail);
                msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SAVE_FAIL + e.getMessage());
            }
            return msg;
        }
        return Result.newFailInstance(SystemConstants.ROLE_FAIL);
    }

    /**
     * 编辑信息
     */
    @RequestMapping("/trail-find")
    public String find(Trail trail) {
        if (null != trail) {
            if (StringUtils.isNotEmpty(trail.getId())) {
                try {
                    trail = trailBiz.findEntityById(trail.getId());
                } catch (QueryException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 删除模版
     */
    @RequestMapping("/trail-delTemplate")
    @ResponseBody
    public String delTemplate() {
        Result msg;
        String id = HttpUtils.getParam("id");
        List<String> properties = new ArrayList<String>();
        try {
            Trail entity = trailBiz.findEntityById(id);

            entity.setCommonTemplate("0");
            properties.add("commonTemplate");
            trailBiz.updateEntity(entity, properties);
            msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
        } catch (QueryException e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.DEL_FAIL + e.getMessage());
        } catch (SaveException e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.DEL_FAIL + e.getMessage());
        }
        msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
        return null;
    }

    /**
     * 删除信息
     */
    @RequestMapping("/trail-del")
    @ResponseBody
    public String del() {
        Result msg;
        /*
         * if(checkRight(RoleConstants.SUP_CUSTOMER_DEL)) {
		 * try {
		 * String ids = HttpUtils.getParam("id");
		 * String[] idArr = ids.split(",");
		 * StringBuffer sb = new StringBuffer();
		 * for(String string : idArr) {
		 * sb.append("'").append(string).append("',");
		 * }
		 * if(sb.length() > 0) {
		 * sb.deleteCharAt(sb.length() - 1);
		 * filters = new Filter();
		 * filters.setGroupOp(FilterGroupOption.AND);
		 * filters.addRule(new SearchRule("ID", SearchRuleOption.in, sb.toString()));
		 * trailBiz.deleteByFilter(filters);
		 * }
		 * msg = MsgConstants.DEL_SUCCES;
		 * } catch (Exception e) {
		 * e.printStackTrace();
		 * msg = MsgConstants.DEL_FAIL + e.getMessage();
		 * }
		 * return msg;
		 * }
		 */
        if (checkRight(RoleConstants.SUP_CUSTOMER_DEL)) {
            try {
                String ids = HttpUtils.getParam("id");
                Trail t = new Trail();
                t.setId(ids);
                trailBiz.delete(t);
                msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.DEL_FAIL + e.getMessage());
            }
        }
        return null;
    }

    /**
     * 供应商业务审核详细页面
     */
    @RequestMapping("/trail-findForSupToValidate")
    public String findForSupToVlidate(Trail trail, CancelReason cancelReason) {
        List<TrailCTAddressDTO> ctAddressDTOList = null;
        List<CancelReason> cancelReasonList = null;
        List<RejectContent> rejectContentList = null;
        String id = HttpUtils.getParam("id");
        String checkType = HttpUtils.getParam("checkType");
        if (StringUtils.isNotEmpty(id)) {
            try {
                trail = trailBiz.findEntityById(id);
                ctAddressDTOList = trailBiz.findTrailContainers(id);
                // 临时存放柜id
                StringBuffer container_tmp = new StringBuffer();
                containers = new ArrayList<Container>();
                // 获取所有的柜，并且对柜进行去重，便于页面去重
                if (trail != null && trail.getGdes() != null) {
                    for (GoodAddress ga : trail.getGdes()) {
                        if (ga.getContainers() != null) {
                            for (Container container : ga.getContainers()) {
                                if (container_tmp.indexOf(container.getId()) == -1) {
                                    container_tmp.append(container.getId()).append(",");
                                    containers.add(container);
                                }
                            }
                        }
                    }
                }
                containerTotle = new HashMap<String, Integer>();
                for (Container container : containers) {
                    String size_Type = container.getCt_size() + "'" + container.getCt_type();
                    if (containerTotle.get(size_Type) == null) {
                        containerTotle.put(size_Type, 1);
                    } else {
                        containerTotle.put(size_Type, containerTotle.get(size_Type) + 1);
                    }
                }
                // 取消申请理由
                cancelReasonList = cancelReasonBiz
                        .findEntityByHql("from com.mrd.gtimp.business.pojo.CancelReason cancelReason where cancelReason.bid = '"
                                + id + "'", 0, 10, null);
                cancelReason = new CancelReason();
                for (CancelReason cr : cancelReasonList) {
                    cancelReason.setCancelDate(cr.getCancelDate());
                    cancelReason.setCancelPerson(cr.getCancelPerson());
                    cancelReason.setContent(cr.getContent());
                }

                // 驳回原因
                rejectContentList = rejectContentBiz
                        .findEntityByHql("from com.mrd.gtimp.business.pojo.RejectContent rejectContent where rejectContent.bid = '"
                                + id + "'", 0, 10, null);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "/gtimp/trail/trailInfoForView1";
    }

    /**
     * 供应商业务审核列表页面
     */
    @RequestMapping("/trail-listForSupToValidate")
    public String listForSupToValidate() {
        return "gtimp/trail/traillistForSupToValidate";
    }

    /**
     * 查询列表给供应商审核业务信息
     */
    @RequestMapping("/trail-findListForSupToValidate")
    public String findListForSupToValidate(User user, Filter filters) {
        Logger log = Logger.getLogger(TrailAction.class);
        String comId = user.getCompany().getId();// 此处为供应商
//        try {
        if (null == filters) {
            filters = new Filter();
            filters.setGroupOp(FilterGroupOption.AND);
        }
        SearchRule rule = new SearchRule("supCompany.id", SearchRuleOption.eq, comId);
        filters.addRule(rule);
        // SearchRule rule2 = new SearchRule("trailState", SearchRuleOption.nc,
        // BaseTypeConstant.TRAILSTATE_00);
        // filters.addRule(rule2);
        trailState = trailState.substring(0, 4);
        if ("TS02".equals(trailState)) {// 通过审核
            SearchRule rule2 = new SearchRule("trailState", SearchRuleOption.eq, BaseTypeConstant.TRAILSTATE_02);
            filters.addRule(rule2);
        } else if ("TS04".equals(trailState)) {// 安排中
            SearchRule rule2 = new SearchRule("trailState", SearchRuleOption.eq, BaseTypeConstant.TRAILSTATE_04);
            filters.addRule(rule2);
        } else if ("TS05".equals(trailState)) {// 已完成
            SearchRule rule2 = new SearchRule("trailState", SearchRuleOption.eq, BaseTypeConstant.TRAILSTATE_05);
            filters.addRule(rule2);
        } else if ("TS07".equals(trailState)) {// 已取消
            SearchRule rule2 = new SearchRule("trailState", SearchRuleOption.eq, BaseTypeConstant.TRAILSTATE_07);
            filters.addRule(rule2);
        } else {// 已下单，待审核,已驳回,取消申请订单
            SearchRule rule2 = new SearchRule("trailState", SearchRuleOption.in, BaseTypeConstant.TRAILSTATE_01
                    + ","
                    + BaseTypeConstant.TRAILSTATE_03
                    + ","
                    + BaseTypeConstant.TRAILSTATE_06);
            filters.addRule(rule2);
        }
        //// TODO: 2016/8/15  page
//            page = initPage(trailBiz.findEntityCount(filters));
//            Order order = new Order();
//            if (null != sidx && !"".equals(sidx)) {
//                order.add(sidx, sord);
//            }

        String listCase = "select sval.chn, trail from com.mrd.gtimp.business.pojo.Trail trail, com.mrd.gtimp.base.pojo.SystemValue sval where trail.trailState=sval.identifier and (1=1 ";
        String whereCase = "";
        if (null != filters.getRules() && filters.getRules().size() > 0) {
            for (SearchRule sr : filters.getRules()) {
                String field = sr.getField();
                Object data = sr.getData();
                if (field.equals("supCompany.id") || field.equals("trailState")) {
                    if (sr.getOp() == SearchRuleOption.eq) {
                        whereCase = whereCase + " and trail." + field + " = '" + data + "' ";
                    } else if (sr.getOp() == SearchRuleOption.nc) {
                        whereCase = whereCase + " and trail." + field + " not in ('" + data
                                + "') ";
                    }
                    // else {
                    // if(sr.getOp() == SearchRuleOption.in) {
                    // whereCase = whereCase + " and trail." + field + " in (" + data
                    // + ")";
                    // } else {
                    // whereCase = whereCase + " and trail." + field + " like '%" + data
                    // + "%' ";
                    // }
                    // }
                }
            }
        }
        // 业务流转查询
        whereCase = whereCase
                + " or trail.id in (select bf.bizId from com.mrd.gtimp.business.pojo.BizFlow bf where bf.scompany='"
                + comId + "' or bf.tcompany='" + comId + "')) ";
        if (null != filters.getRules() && filters.getRules().size() > 0) {
            for (SearchRule sr : filters.getRules()) {
                String field = sr.getField();
                Object data = sr.getData();
                Field f = ReflectUtil.getField(sr.getField(), Trail.class);
                boolean isDate = false;
                if (f != null) {
                    if (f.getType().equals(Date.class)) {
                        data = "to_date('" + data + "','yyyy-MM-dd')";
                        isDate = true;
                    }
                }
                if (!"supCompany.id".equals(field)
                        && !data.equals(BaseTypeConstant.TRAILSTATE_00)) {
                    if (sr.getOp() == SearchRuleOption.eq) {
                        whereCase = whereCase + " and trail." + field + " = '" + data + "' ";
                    } else if (sr.getOp() == SearchRuleOption.nc) {
                        whereCase = whereCase + " and trail." + field + " not in ('" + data
                                + "') ";
                    } else if (sr.getOp().equals(SearchRuleOption.gt)) {
                        whereCase = whereCase + " and trail." + field
                                + (isDate ? " > " + data : " > '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.lt)) {
                        whereCase = whereCase + " and trail." + field
                                + (isDate ? " < " + data : " < '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.ge)) {
                        whereCase = whereCase + " and trail." + field
                                + (isDate ? " >= " + data : " >= '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.le)) {
                        whereCase = whereCase + " and trail." + field
                                + (isDate ? " <= " + data : " <= '" + data + "'");
                    } else {
                        if (field.equals("so")) {
                            whereCase = whereCase
                                    + " and trail.id in (select ct.trail from com.mrd.gtimp.business.pojo.Container ct where ct.so = '"
                                    + data + "') ";
                        } else if (field.equals("reqNo")) {
                            whereCase = whereCase
                                    + " and trail.id in (select ct.trail from com.mrd.gtimp.business.pojo.Container ct where ct.reqNo = '"
                                    + data + "')";
                        } else {
                            if (sr.getOp() == SearchRuleOption.in) {
                                data = "'" + data.toString().substring(0, 4) + "'" + "," + "'"
                                        + data.toString().substring(5, 9) + "'" + "," + "'"
                                        + data.toString().substring(10, 14) + "'";
                                whereCase = whereCase + " and trail." + field + " in (" + data
                                        + ")";
                            } else {
                                whereCase = whereCase + " and trail." + field + " like '%"
                                        + data + "%'";
                            }
                        }
                        // whereCase = whereCase + " and trail." + field + " like '%" + data
                        // + "%'";
                    }
                }
            }
        }
        //// TODO: 2016/8/15  order
//            for (String key : order.keySet()) {
//                whereCase = whereCase + " order by trail." + key + " "
//                        + (order.get(key) ? "desc" : "asc") + " ";
//            }
//            listCase = listCase + whereCase;
//            List<Object> objList = trailBiz
//                    .findObjectByHql(listCase, page.getCurrentPageStartNo(), page.getPageSize(), null);
//            if (null != objList && objList.size() > 0) {
//                if (trails == null) {
//                    trails = new ArrayList<Trail>();
//                }
//                for (Object o : objList) {
//                    Object[] os = (Object[]) o;
//                    Trail b = (Trail) os[1];
//                    List<GoodAddress> list = b.getGdes();
//                    String so = "";
//                    String reqNo = "";
//                    for (GoodAddress g : list) {
//                        if ("".equals(so)) {
//                            so = g.getSo();
//                        } else {
//                            so = g.getSo() + "," + so;
//                        }
//                        for (Container ct : g.getContainers()) {
//                            if ("".equals(reqNo)) {
//                                reqNo = ct.getReqNo();
//                            } else {
//                                reqNo = ct.getReqNo() + "," + reqNo;
//                            }
//                        }
//                    }
//                    if (so != null && !"".equals(so)) {
//                        so = removeDuplicateSo(so);// so去重
//                    }
//                    if (reqNo != null && !"".equals(reqNo)) {
//                        reqNo = removeDuplicateSo(reqNo); // reqNo去重
//                    }
//                    b.setSo(so);
//                    b.setReqNo(reqNo);
//                    b.setTrailState(SpecialConstant.VALIDATE_STATE_CUSTOMER_VIEW.equals(os[0]
//                            .toString()) ? SpecialConstant.VALIDATE_STATE_SUP_VIEW : os[0]
//                            .toString());
//                    String realSupId = b.getRealSupId();
//                    if (StringUtils.isNotEmpty(realSupId)) {
//                        if (realSupId.equals(comId)) {
//                            b.setRealSupId(realSupId + ":业务流入");
//                        } else {
//                            b.setRealSupId(realSupId + ":业务流出");
//                        }
//                    }
//                    trails.add(b);
//                }
//            }
//        } catch (QueryException e) {
//            e.printStackTrace();
//        }
        //// TODO: 2016/8/15
//        return "gridDataForSupToValidate";
        return null;
    }

    @RequestMapping("/trail-checkValidatePass")
    @ResponseBody
    public String checkValidatePass() {
        Result msg;
        String id = HttpUtils.getParam("id");
        String opType = HttpUtils.getParam("opType");
        if (StringUtils.isNotEmpty(id)) {
            try {
                String hql = "select trail.trailState from com.mrd.gtimp.business.pojo.Trail trail where trail.id='"
                        + id + "'";
                List<Object> objlist = trailBiz.findObjectByHql(hql, 0, 1, null);
                if (null != objlist && objlist.size() == 1) {
                    if ("tgsh".equals(opType) || "bh".equals(opType)) {
                        if (BaseTypeConstant.TRAILSTATE_01.equals(objlist.get(0))) {
                            msg = Result.newSuccessInstance(MsgConstants.CHECK_SUCCESS);
                        } else {
                            msg = Result.newFailInstance(MsgConstants.CHECK_FAIL);
                        }
                    } else {
                        if (BaseTypeConstant.TRAILSTATE_02.equals(objlist.get(0))) {
                            msg = Result.newSuccessInstance(MsgConstants.CHECK_SUCCESS);
                        } else {
                            msg = Result.newFailInstance(MsgConstants.CHECK_FAIL);
                        }
                    }

                } else {
                    msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
                }
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
            }
        } else {
            msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
        }
        //// TODO: 2016/8/17 json msg
        return null;
    }

    public String checkValidateReject() {
        return checkValidatePass();
    }

    @RequestMapping("/trail-validatePass")
    @ResponseBody
    public Result validatePass(Trail trail) {
        Result msg;
        try {
            String id = HttpUtils.getParam("id");
            trail = trailBiz.findEntityById(id);
            if (null != trail && trail.getTrailState().equals(BaseTypeConstant.TRAILSTATE_01)) {
                trailBiz.updateValidatePass(id);
                msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
                String userName = trail.getCreator();
                String businessId = trail.getBusinessId();
                List<User> userList = userBiz
                        .findEntityByHql("from com.mrd.gtimp.base.pojo.User where account = '"
                                + userName + "'", 0, 10, null);
                if (userList.size() > 0) {
                    String user_email = userList.get(0).getEmail();
                    String body = "您拖车业务单已经通过审核，业务编号为：" + businessId;
                    SendEmail.sendEmail(user_email, "货运平台审核通知", body);
                }
            } else {
                msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            }
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    @RequestMapping("/trail-validateReject")
    @ResponseBody
    public Result validateReject(Trail trail) {
        Result msg;
        try {
            String id = HttpUtils.getParam("id");
            trail = trailBiz.findEntityById(id);
            if (null != trail && trail.getTrailState().equals(BaseTypeConstant.TRAILSTATE_01)) {
                trailBiz.updateValidateReject(id);
                msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
            } else {
                msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            }
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 保存为常用模板
     */
    @RequestMapping("/trail-saveAsModel")
    @ResponseBody
    public Result saveAsModel(Trail trail) throws QueryException {
        Result msg;
        String id = HttpUtils.getParam("id");
        String commonTemplateName = trail.getCommonTemplateName();
        try {
            // trail = trailBiz.findEntityById(id);
            // if("1".equals(trail.getCommonTemplate())) {
            // msg = MsgConstants.IS_COMMONTEMPLATE;
            // } else {
            trail = new Trail();
            List<String> properties = new ArrayList<String>();
            trail.setId(id);
            trail.setCommonTemplate("1");
            trail.setCommonTemplateName(commonTemplateName);
            properties.add("commonTemplate");
            properties.add("commonTemplateName");
            trailBiz.updateEntity(trail, properties);
            msg = Result.newSuccessInstance(MsgConstants.SAVEMODEL_SUCCESS);
            // }

        } catch (Exception e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.SAVEMODEL_FAIL);
        }
        return msg;
    }

    @Resource
    public void setTrailBiz(TrailBiz trailBiz) {
        this.trailBiz = trailBiz;
    }


    public List<Container> getContainers() {
        return containers;
    }

    public void setContainers(List<Container> containers) {
        this.containers = containers;
    }

    public Map<String, Integer> getContainerTotle() {
        return containerTotle;
    }

    public void setContainerTotle(Map<String, Integer> containerTotle) {
        this.containerTotle = containerTotle;
    }

    public String getLoadPage() {
        return loadPage;
    }

    public void setLoadPage(String loadPage) {
        this.loadPage = loadPage;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getIdentify() {
        return identify;
    }

    public void setIdentify(String identify) {
        this.identify = identify;
    }

    /**
     * 业务查看入口
     */
    @RequestMapping("/trail-bizView")
    public String bizView() {
//        findForSupToValidate();
        String checkType = HttpUtils.getParam("checkType");
        HttpUtils.getRequest().setAttribute("checkType", checkType);
        // if("C".equals(checkType)) {
        // return "bizViewForCustom";
        // } else {
        // return "bizView";
        // }
        return "/gtimp/trail/trailInfoForView1";
    }

    /**
     * 业务修改入口
     */
    @RequestMapping("/trail-bizModify")
    public String bizModify() {
        ///// TODO: 2016/8/15
        return "bizModify";
    }

    /**
     * 检查业务是否可以进入修改页面
     */
    @RequestMapping("/trail-checkBizModify")
    @ResponseBody
    public Result checkBizModify() {
        Result msg;
        String id = HttpUtils.getParam("id");
        if (StringUtils.isNotEmpty(id)) {
            try {
                String hql = "select trail.trailState from com.mrd.gtimp.business.pojo.Trail trail where trail.id='"
                        + id + "'";
                List<Object> objlist = trailBiz.findObjectByHql(hql, 0, 1, null);
                if (null != objlist && objlist.size() == 1) {
                    if (BaseTypeConstant.TRAILSTATE_03.equals(objlist.get(0))
                            || BaseTypeConstant.TRAILSTATE_00.equals(objlist.get(0))) {
                        msg = Result.newSuccessInstance(MsgConstants.CHECK_SUCCESS);
                    } else {
                        msg = Result.newFailInstance(MsgConstants.CHECK_FAIL);
                    }
                } else {
                    msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
                }
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
            }
        } else {
            msg = Result.newFailInstance(MsgConstants.SYSTEM_ERROR);
        }
        return msg;
    }

    /**
     * 检查业务是否可以进行提交操作
     */
    @RequestMapping("/trail-checkBizConfirm")
    public Result checkBizConfirm() {
        return checkBizModify();
    }

    /**
     * 业务提交
     */
    @RequestMapping("/trail-bizConfirm")
    @ResponseBody
    public Result bizConfirm(Trail trail) {
        Result msg;
        try {
            trail = trailBiz.findEntityById(id);
            if (trail.getTrailState().equals(BaseTypeConstant.TRAILSTATE_00)
                    || trail.getTrailState().equals(BaseTypeConstant.TRAILSTATE_03)) {
                trailBiz.updateBizConfirm(id);
                msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
                String businessId = trail.getBusinessId();
                String sendMail = HttpUtils.getParam("sendMail");
                if ("Y".equals(sendMail)) {
                    // 提交后进行消息提醒
                    // RobotService.sendMsgToUserClient("gtimp/biz/guanxx", businessId);
                    // 拖车列表,修改页面提交后邮件，短信发送
                    String user_email = "";
                    String user_phone = "";
                    String body = "您有新的拖车业务单,业务编号为：" + businessId + ",请尽快处理!";
                    if ("佛山新港".equals(trail.getSupCompany().getName())) {
                        List<User> userList = userBiz
                                .findEntityByHql("from com.mrd.gtimp.base.pojo.User where account in ('chenwc','niepy')", 0, 10, null);
                        if (userList.size() > 0) {
                            for (User u : userList) {
                                user_email = u.getEmail();
                                if (user_email != null) {
                                    SendEmail.sendEmail(user_email, "货运平台下单通知", body);
                                }
                                // 修改页面提交后短信发送
                                // user_phone = u.getMobile();
                                // if(user_phone != null || !"".equals(user_phone)) {
                                // com.mrd.util.sendMessage.SendMessageAct
                                // .doSendPhoneMsg(user_phone, body);
                                // }
                            }
                        }
                    } else if ("宏达货代".equals(trail.getSupCompany().getName())) {
                        List<User> userList = userBiz
                                .findEntityByHql("from com.mrd.gtimp.base.pojo.User where account in ('yaozd','zouyf','xiey','zoucl','zhoud')", 0, 10, null);
                        if (userList.size() > 0) {
                            for (User u : userList) {
                                user_email = u.getEmail();
                                if (user_email != null) {
                                    SendEmail.sendEmail(user_email, "货运平台下单通知", body);
                                }
                                // 修改页面提交后短信发送
                                // user_phone = u.getMobile();
                                // if(user_phone != null || !"".equals(user_phone)) {
                                // com.mrd.util.sendMessage.SendMessageAct
                                // .doSendPhoneMsg(user_phone, body);
                                // }
                            }
                        }
                    }
                }

            } else {
                msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            }
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 拖车供应商取消订单
     */
    @RequestMapping("/trail-supCancelBill")
    @ResponseBody
    public Result supCancelBill() {
        Result msg = null;
        String id = HttpUtils.getParam("id");
        if (StringUtils.isNotEmpty(id)) {
            try {
                trailBiz.updateValidateCancel(id);
                msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
            } catch (Exception e) {
                msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
                e.printStackTrace();
            }
        }
        return msg;
    }

    /**
     * 查询
     */
    // TODO: 2016/8/17 d
    @RequestMapping("/trail-saveAsModel-data")
    public String findList(User user, Filter filters) {
        String comId = user.getCompany().getId();// 此处为客户
        try {
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            SearchRule rule = new SearchRule("customer.id", SearchRuleOption.eq, comId);
            filters.addRule(rule);
            //// TODO: 2016/8/15  page
//            page = initPage(trailBiz.findEntityCount(filters));
//            Order order = new Order();
//            if (null != sidx && !"".equals(sidx)) {
//                order.add(sidx, sord);
//            }

            String listCase = "select sval.chn, trail from com.mrd.gtimp.business.pojo.Trail trail, com.mrd.gtimp.base.pojo.SystemValue sval where trail.trailState=sval.identifier ";
            String whereCase = "";
            if ("load".equals(loadPage)) {
                // whereCase = whereCase
                // +
                // " and trail.trailState in('TS02','TS04','TS05')";
                // 草稿状态之后成功保存为常用模板条件
                whereCase = whereCase + " and trail.commonTemplate = '1'";
            }
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    Field f = ReflectUtil.getField(sr.getField(), Trail.class);
                    boolean isDate = false;
                    if (f != null) {
                        if (f.getType().equals(Date.class)) {
                            data = "to_date('" + data + "','yyyy-MM-dd')";
                            isDate = true;
                        }
                    }

                    if (sr.getOp() == SearchRuleOption.eq) {
                        whereCase = whereCase + " and trail." + field + " = '" + data + "' ";
                    } else if (sr.getOp() == SearchRuleOption.nc) {
                        whereCase = whereCase + " and trail." + field + " not in ('" + data + "') ";
                    } else if (sr.getOp().equals(SearchRuleOption.gt)) {
                        whereCase = whereCase + " and trail." + field
                                + (isDate ? " > " + data : " > '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.lt)) {
                        whereCase = whereCase + " and trail." + field
                                + (isDate ? " < " + data : " < '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.ge)) {
                        whereCase = whereCase + " and trail." + field
                                + (isDate ? " >= " + data : " >= '" + data + "'");
                    } else if (sr.getOp().equals(SearchRuleOption.le)) {
                        whereCase = whereCase + " and trail." + field
                                + (isDate ? " <= " + data : " <= '" + data + "'");
                    } else {
                        if (field.equals("so")) {
                            whereCase = whereCase
                                    + " and trail.id in (select ct.trail from com.mrd.gtimp.business.pojo.Container ct where ct.so = '"
                                    + data + "') ";
                        } else {
                            whereCase = whereCase + " and trail." + field + " like '%" + data
                                    + "%' ";
                        }
                    }
                }
            }
            //// TODO: 2016/8/15  order page
//            for (String key : order.keySet()) {
//                whereCase = whereCase + " order by trail." + key + " "
//                        + (order.get(key) ? "desc" : "asc") + " ";
//            }
//            listCase = listCase + whereCase;
//            List<Object> objList = trailBiz
//                    .findObjectByHql(listCase, page.getCurrentPageStartNo(), page.getPageSize(), null);
//            if (null != objList && objList.size() > 0) {
//                if (trails == null) {
//                    trails = new ArrayList<Trail>();
//                }
//                for (Object o : objList) {
//                    Object[] os = (Object[]) o;
//                    Trail b = (Trail) os[1];
//                    List<GoodAddress> list = b.getGdes();
//                    String so = "";
//                    for (GoodAddress g : list) {
//                        // if("".equals(so)) {
//                        // so = g.getSo();
//                        // } else {
//                        // so = g.getSo() + "," + so;
//                        // }
//                        // for(Container ct : g.getContainers()) {
//                        if ("".equals(so)) {
//                            so = g.getSo();
//                        } else {
//                            so = g.getSo() + "," + so;
//                        }
//                        // }
//                    }
//                    if (so != null && !"".equals(so)) {
//                        so = removeDuplicateSo(so);// so去重
//                    }
//
//                    b.setSo(so);
//                    b.setTrailState(os[0].toString());
//                    trails.add(b);
//                }
//            }
//        } catch (QueryException e) {
        } catch (Exception e) {
            e.printStackTrace();
        }
        //// TODO: 2016/8/15
//            return "gridData";
        return null;
    }

    /**
     * 对重复的so号去重
     */
    @RequestMapping("/trail-removeDuplicateSo")
    public String removeDuplicateSo(String str) {
        String[] s = str.split(",");

        TreeSet<String> tr = new TreeSet<String>();
        for (String element : s) {
            if (!"null".equals(element)) {
                tr.add(element);
            }
        }
        String[] s2 = new String[tr.size()];
        String so = "";
        for (int i = 0; i < s2.length; i++) {
            s2[i] = tr.pollFirst();// 从TreeSet中取出元素重新赋给数组
            so = so + s2[i] + ",";
        }
        if (!"".equals(so)) {
            so = so.substring(0, so.length() - 1);
        }
        return so;
    }

    @RequestMapping("/trail-exportExcel")
    public String exportExcel(User user) {
        List<Trail> trails = null;
        Filter filters = null;
        WritableWorkbook writableWorkbook = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            this.exlFileName = sdf.format(new Date()) + ".xls";

            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024000);
            writableWorkbook = Workbook.createWorkbook(bos);
            int i = 0;

            String comId = user.getCompany().getId();// 供应商ID
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            SearchRule rule = new SearchRule("supCompany.id", SearchRuleOption.eq, comId);
            filters.addRule(rule);
            SearchRule rule2 = new SearchRule("trailState", SearchRuleOption.nc, BaseTypeConstant.TRAILSTATE_00);
            filters.addRule(rule2);
//            page = initPage(trailBiz.findEntityCount(filters));
//            Order order = new Order();
//            if (null != sidx && !"".equals(sidx)) {
//                order.add(sidx, sord);
//            }

            String listCase = "select sval.chn, trail from com.mrd.gtimp.business.pojo.Trail trail, com.mrd.gtimp.base.pojo.SystemValue sval where trail.trailState=sval.identifier and (1=1 ";
            String whereCase = "";

            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    if (field.equals("supCompany.id") || field.equals("trailState")) {
                        if (sr.getOp() == SearchRuleOption.eq) {
                            whereCase = whereCase + " and trail." + field + " = '" + data + "' ";
                        } else if (sr.getOp() == SearchRuleOption.nc) {
                            whereCase = whereCase + " and trail." + field + " not in ('" + data
                                    + "') ";
                        } else {
                            whereCase = whereCase + " and trail." + field + " like '%" + data
                                    + "%' ";
                        }
                    }
                }
            }
            // 业务流转查询
            whereCase = whereCase
                    + " or trail.id in (select bf.bizId from com.mrd.gtimp.business.pojo.BizFlow bf where bf.scompany='"
                    + comId + "' or bf.tcompany='" + comId + "')) ";
            if (null != filters.getRules() && filters.getRules().size() > 0) {
                for (SearchRule sr : filters.getRules()) {
                    String field = sr.getField();
                    Object data = sr.getData();
                    Field f = ReflectUtil.getField(sr.getField(), Trail.class);
                    boolean isDate = false;
                    if (f != null) {
                        if (f.getType().equals(Date.class)) {
                            data = "to_date('" + data + "','yyyy-MM-dd')";
                            isDate = true;
                        }
                    }
                    if (!"supCompany.id".equals(field)
                            && !data.equals(BaseTypeConstant.TRAILSTATE_00)) {
                        if (sr.getOp() == SearchRuleOption.eq) {
                            whereCase = whereCase + " and trail." + field + " = '" + data + "' ";
                        } else if (sr.getOp() == SearchRuleOption.nc) {
                            whereCase = whereCase + " and trail." + field + " not in ('" + data
                                    + "') ";
                        } else if (sr.getOp().equals(SearchRuleOption.gt)) {
                            whereCase = whereCase + " and trail." + field
                                    + (isDate ? " > " + data : " > '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.lt)) {
                            whereCase = whereCase + " and trail." + field
                                    + (isDate ? " < " + data : " < '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.ge)) {
                            whereCase = whereCase + " and trail." + field
                                    + (isDate ? " >= " + data : " >= '" + data + "'");
                        } else if (sr.getOp().equals(SearchRuleOption.le)) {
                            whereCase = whereCase + " and trail." + field
                                    + (isDate ? " <= " + data : " <= '" + data + "'");
                        } else {
                            if (field.equals("so")) {
                                whereCase = whereCase
                                        + " and trail.id in (select ct.trail from com.mrd.gtimp.business.pojo.Container ct where ct.so = '"
                                        + data + "') ";
                            } else if (field.equals("reqNo")) {
                                whereCase = whereCase
                                        + " and trail.id in (select ct.trail from com.mrd.gtimp.business.pojo.Container ct where ct.reqNo = '"
                                        + data + "')";
                            } else {
                                whereCase = whereCase + " and trail." + field + " like '%" + data
                                        + "%'";
                            }
                            // whereCase = whereCase + " and trail." + field + " like '%" + data
                            // + "%'";
                        }
                    }
                }
            }
            //// TODO: 2016/8/15  order page
//            for (String key : order.keySet()) {
//                whereCase = whereCase + " order by trail." + key + " "
//                        + (order.get(key) ? "desc" : "asc") + " ";
//            }
//            listCase = listCase + whereCase;
//            // List<Object> objList = trailBiz
//            // .findObjectByHql(listCase, page.getCurrentPageStartNo(), page.getPageSize(), null);
//            List<Object> objList = trailBiz.findObjectByHql(listCase, 0, page.getPageSize(), null);
//            if (null != objList && objList.size() > 0) {
//                if (trails == null) {
//                    trails = new ArrayList<Trail>();
//                }
//                for (Object o : objList) {
//                    Object[] os = (Object[]) o;
//                    Trail b = (Trail) os[1];
//                    List<GoodAddress> list = b.getGdes();
//                    String so = "";
//                    String reqNo = "";
//                    for (GoodAddress g : list) {
//                        if ("".equals(so)) {
//                            so = g.getSo();
//                        } else {
//                            so = g.getSo() + "," + so;
//                        }
//                        for (Container ct : g.getContainers()) {
//
//                            if ("".equals(reqNo)) {
//                                reqNo = ct.getReqNo();
//                            } else {
//                                reqNo = ct.getReqNo() + "," + reqNo;
//                            }
//                        }
//                    }
//                    if (so != null && !"".equals(so)) {
//                        so = removeDuplicateSo(so);// so去重
//                    }
//                    if (reqNo != null && !"".equals(reqNo)) {
//                        reqNo = removeDuplicateSo(reqNo); // reqNo去重
//                    }
//                    b.setSo(so);
//                    b.setReqNo(reqNo);
//                    b.setTrailState(SpecialConstant.VALIDATE_STATE_CUSTOMER_VIEW.equals(os[0]
//                            .toString()) ? SpecialConstant.VALIDATE_STATE_SUP_VIEW : os[0]
//                            .toString());
//
//                    trails.add(b);
//                }
//            }

            WritableSheet sheet = writableWorkbook.createSheet("拖车详细列表", i);

            // 设置字体种类和格式
            WritableFont bold = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
            WritableCellFormat wcfFormat = new WritableCellFormat(bold);
            wcfFormat.setAlignment(jxl.format.Alignment.CENTRE);// 单元格中的内容水平方向居中

            sheet.setRowView(0, 500);
            // sheet.addCell(new Label(0, 0, "拖车列表信息"));
            sheet.addCell(new Label(0, 0, "拖车列表信息", wcfFormat));
            sheet.mergeCells(0, 0, 8, 0);

            String[] str = {"业务编号", "交接单号", "业务委托人", "实际托运人", "SO号", "业务提交时间", "审核状态", "审核人",
                    "审核时间"};
            int n = 0;
            for (int k = 0; k < str.length; k++) {
                sheet.setColumnView(n, 20);// 设置列的宽度
                sheet.addCell(new Label(n, 1, str[k]));
                n++;
            }

            for (int row = 0; row < trails.size(); row++) {
                Trail trail = trails.get(row);
                sheet.addCell(new Label(0, row + 2, trail.getBusinessId()));
                sheet.addCell(new Label(1, row + 2, trail.getReqNo()));
                sheet.addCell(new Label(2, row + 2, trail.getCustomer().getName()));
                sheet.addCell(new Label(3, row + 2, trail.getShipper().getCompany()));
                sheet.addCell(new Label(4, row + 2, trail.getSo()));
                String confirm_time = trail.getConfirmTime().toString();
                sheet.addCell(new Label(5, row + 2, confirm_time.substring(0, confirm_time.length() - 2)));
                sheet.addCell(new Label(6, row + 2, trail.getTrailState()));
                if (trail.getValidator() != null) {
                    sheet.addCell(new Label(7, row + 2, trail.getValidator().getName()));
                }
                if (trail.getValidateTime() != null) {
                    String validate_time = trail.getValidateTime().toString();
                    sheet.addCell(new Label(8, row + 2, validate_time.substring(0, validate_time
                            .length() - 2)));
                }
            }

            writableWorkbook.write();
            writableWorkbook.close();
            this.ExlStream = new ByteArrayInputStream(bos.toByteArray());
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //// TODO: 2016/8/15  stream
//        return "exportExcel";
        return null;
    }

    /**
     * 保存模板命名页面
     */
    @RequestMapping("/trail-saveAsModelName")
    public String saveAsModelName() {
        return "/gtimp/trail/saveAsTrailModelName";
    }


    public String getExlFileName() {
        return exlFileName;
    }

    public void setExlFileName(String exlFileName) {
        this.exlFileName = exlFileName;
    }

    public InputStream getExlStream() {
        return ExlStream;
    }

    public void setExlStream(InputStream exlStream) {
        ExlStream = exlStream;
    }

    public String getTrailState() {
        return trailState;
    }

    public void setTrailState(String trailState) {
        this.trailState = trailState;
    }

}
